package web.exercise.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlOperationUtil {
	//两个工具，对xml的读取和写入
	public static Document getDocument(){
		File file=new File("e:/contacts.xml");
		Document doc=null;
		try{
			if(!file.exists()){
				//若文件不存在，则先创建文件，然后创建文档，最后创建根节点
				file.createNewFile();
				doc=DocumentHelper.createDocument();
				doc.addElement("contacts");
			}
			doc=new SAXReader().read(file);
			return doc;
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	//写入
	public static void write(Document doc){
		File file=new File("e:/contacts.xml");
		try{
			//以输出字符流的方式写入doc数据
			FileOutputStream buf=new FileOutputStream(file);
			OutputFormat format=OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			XMLWriter writer=new XMLWriter(buf,format);
			writer.write(doc);
			writer.close();
		}catch(IOException e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
}
